package com.vk.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.vk.project.common.*;
import com.vk.project.exception.BusinessException;
import com.vk.project.model.dto.user.*;
import com.vk.project.model.vo.EmailRegisterVO;
import com.vk.project.model.vo.UserVO;
import com.vk.project.service.UserService;
import com.vk.vkapicommon.model.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolderStrategy;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Email;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.stream.Collectors;

import static com.vk.project.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @ClassName : UserController
 * @Description : 用户管理控制器
 * @Author : LYQ
 * @Date: 2023-12-08 15:23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户信息
     *
     * @param request 当前会话
     * @return 返回用户信息
     */
    @GetMapping("/getLoginUser")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        if(loginUser != null){
            UserVO loginUserVO = new UserVO();
            BeanUtils.copyProperties(loginUser, loginUserVO);
            return ResultUtils.success(loginUserVO);
        }
        return ResultUtils.error(501,"获取登录用户信息失败！");
    }

    /**
     * 请求邮件验证码
     * @param email 请求邮件
     * @param type 类型
     * @param request 请求
     * @return 是否请求成功
     */
    @GetMapping("/ask-code")
    public BaseResponse<String> asVerifyCode(@RequestParam @Email String email,
                                       @RequestParam @Pattern(regexp = "(register|reset)") String type,
                                       HttpServletRequest request) {
        String result = userService.registerEmailVerifyCode(type, String.valueOf(email), request.getRemoteAddr());
        if(result == null) {
            // 返回成功结果
            return ResultUtils.success(result);
        }
        // 返回失败结果
        return ResultUtils.error(520,"获取验证码失败！");
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求对象
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<String> userRegister(@RequestBody EmailRegisterVO emailRegisterVO) {
        // 如果用户注册请求为空，抛出参数错误异常
        if (emailRegisterVO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取用户账号、密码和确认密码
        String username = emailRegisterVO.getUsername();
        String password = emailRegisterVO.getPassword();
        String passwordRepeat = emailRegisterVO.getPasswordRepeat();
        // 如果用户账号、密码或确认密码有空值，返回null
        if (StringUtils.isAnyBlank(username, password, passwordRepeat)) {
            return null;
        }
        // 调用用户服务层的用户注册方法，获取结果
        String result = userService.registerEmailAccount(emailRegisterVO);
        if(result == null) {
            // 返回成功结果
            return ResultUtils.success(result);
        }
        // 返回失败结果
        return ResultUtils.error(510,"用户注册失败！");
    }

    /**
     * 创建用户
     *
     * @param userAddRequest 用户创建请求对象
     * @param request        请求体
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        // 调用用户服务层的用户注册方法，获取结果
        String result = userService.addUser(userAddRequest, request);
        if(result == null) {
            // 返回成功结果
            return ResultUtils.success(result);
        }
        // 返回失败结果
        return ResultUtils.error(510, "用户注册失败！" + result);
    }

    /**
     * 删除用户
     *
     * @param deleteRequest 删除请求对象
     * @param request       请求体
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody IdListRequest idListRequest, HttpServletRequest request) {
        boolean deleted = userService.deleteUserById(idListRequest, request);
        return ResultUtils.success(deleted);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest 用户更新请求对象
     * @param request           请求体
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        boolean updated = userService.updateUser(userUpdateRequest, request);
        // 返回更新结果
        return ResultUtils.success(updated);
    }

    /**
     * 根据Id获取用户信息
     *
     * @param id      用户Id
     * @param request 请求体
     * @return 返回用户信息的响应对象
     */
    @GetMapping("/get/{id}")
    public BaseResponse<UserVO> getUserById(@PathVariable int id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 根据用户ID查询用户信息
        User user = userService.getById(id);
        // 将用户信息拷贝到UserVO对象中
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        // 返回用户信息的响应对象
        return ResultUtils.success(userVO);
    }

    /**
     * 获取用户列表
     *
     * @param userQueryRequest 用户查询请求对象
     * @param request          请求体
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        // 创建User对象
        User userQuery = new User();
        // 如果传入的用户查询请求不为空，则将其中的属性复制到User对象中
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
        }
        // 创建QueryWrapper对象，将User对象传入
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        // 根据QueryWrapper对象查询出用户列表
        List<User> userList = userService.list(queryWrapper);
        // 将用户列表转换为UserVO列表
        List<UserVO> userVOList = userList.stream().map(user -> {
            // 创建UserVO对象
            UserVO userVO = new UserVO();
            // 将User对象中的属性复制到UserVO对象中
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        // 返回UserVO列表
        return ResultUtils.success(userVOList);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest 用户查询请求
     * @param request          请求体
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<UserVO>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest, HttpServletRequest request) {
        Page<UserVO> userVOPage = userService.listUserByPage(userQueryRequest, request);
        // 返回用户列表的分页信息
        return ResultUtils.success(userVOPage);
    }
}
